package com.dctp.ems.utils;

import com.dctp.ems.vo.AggregatedResult;
import com.jfinal.plugin.activerecord.Record;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderAggregator {

    public static List<AggregatedResult> aggregateToList(List<Record> records) {
        Map<String, AggregatedResult> aggregationMap = new HashMap<>();

        for (Record r : records) {
            String symbol = r.getStr("symbol");
            Integer direction = r.getInt("direction");

            BigDecimal quantity = r.getBigDecimal("total_quantity");
            if (null == quantity)  quantity = BigDecimal.ZERO;
            BigDecimal pnl = r.getBigDecimal("total_realized_pnl");
            if (null == pnl)  pnl = BigDecimal.ZERO;
            BigDecimal fee = r.getBigDecimal("total_service_fee");
            if (null == fee)  fee = BigDecimal.ZERO;

            AggregatedResult agg = aggregationMap.computeIfAbsent(symbol, s -> {
                AggregatedResult ar = new AggregatedResult();
                ar.symbol = symbol;
                return ar;
            });

            // 总计
            agg.totalQuantity = agg.totalQuantity.add(quantity);
            agg.totalPnl = agg.totalPnl.add(pnl);
            agg.totalFee = agg.totalFee.add(fee);

            // 按 direction 聚合
            if (direction == 1) {
                agg.longQuantity = agg.longQuantity.add(quantity);
                agg.longPnl = agg.longPnl.add(pnl);
                agg.longFee = agg.longFee.add(fee);
            } else if (direction == 2) {
                agg.shortQuantity = agg.shortQuantity.add(quantity);
                agg.shortPnl = agg.shortPnl.add(pnl);
                agg.shortFee = agg.shortFee.add(fee);
            }
        }

        return new ArrayList<>(aggregationMap.values());
    }
}
